/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.peng.commdit.service.impl;

import me.peng.commdit.domain.CommodityManage;
import me.peng.service.impl.FileServiceImpl;
import me.peng.utils.ValidationUtil;
import me.peng.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.peng.commdit.repository.CommodityManageRepository;
import me.peng.commdit.service.CommodityManageService;
import me.peng.commdit.service.dto.CommodityManageDto;
import me.peng.commdit.service.dto.CommodityManageQueryCriteria;
import me.peng.commdit.service.mapstruct.CommodityManageMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.peng.utils.PageUtil;
import me.peng.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* 商品管理
* @author pengjinaye
* @date 2021-10-08
**/
@Service
@RequiredArgsConstructor
public class CommodityManageServiceImpl implements CommodityManageService {

    private final CommodityManageRepository commodityManageRepository;
    private final CommodityManageMapper commodityManageMapper;

    @Override
    public Map<String,Object> queryAll(CommodityManageQueryCriteria criteria, Pageable pageable){
        Page<CommodityManage> page = commodityManageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(commodityManageMapper::toDto));
    }

    @Override
    public List<CommodityManageDto> queryAll(CommodityManageQueryCriteria criteria){
        return commodityManageMapper.toDto(commodityManageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public CommodityManageDto findById(Integer id) {
        CommodityManage commodityManage = commodityManageRepository.findById(id).orElseGet(CommodityManage::new);
        ValidationUtil.isNull(commodityManage.getId(),"CommodityManage","id",id);
        return commodityManageMapper.toDto(commodityManage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommodityManageDto create(CommodityManage resources) {
        return commodityManageMapper.toDto(commodityManageRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CommodityManage resources) {
        CommodityManage commodityManage = commodityManageRepository.findById(resources.getId()).orElseGet(CommodityManage::new);
        ValidationUtil.isNull( commodityManage.getId(),"CommodityManage","id",resources.getId());
        commodityManage.copy(resources);
        commodityManageRepository.save(commodityManage);
    }


    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {

            //根据对应id删除文件数据
            Optional<CommodityManage> resul=commodityManageRepository.findById(id);

            if (resul.isPresent()&&resul.get().getProduconver()!=null){
                //删除封面图片资源
                FileServiceImpl.deleteFileData(resul.get().getProduconver());
            }
            //删除轮播
            if (resul.isPresent()&&resul.get().getCommcarousel()!=null){
                //切割
                String[] carouse=resul.get().getCommcarousel().split(",");
                for (String s:carouse){
                    //传递url地址，进行删除
                    FileServiceImpl.deleteFileData(s);
                }
            }
            //删除详情
            if (resul.isPresent()&&resul.get().getDetailsMap()!=null) {
                //切割
                String[] details = resul.get().getDetailsMap().split(",");
                for (String s : details) {
                    //传递url地址
                    FileServiceImpl.deleteFileData(s);
                }
            }

            commodityManageRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<CommodityManageDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CommodityManageDto commodityManage : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("商品名称", commodityManage.getProductName());
            map.put("商品规格", commodityManage.getSpecifi());
            map.put("商品封面", commodityManage.getProduconver());
            map.put("商品轮播图", commodityManage.getCommcarousel());
            map.put("商品分类", commodityManage.getCategories());
            map.put("商品详情", commodityManage.getProdudetails());
            map.put("商品状态", commodityManage.getStatus());
            map.put("商品价格", commodityManage.getPrice());
            map.put("运费", commodityManage.getFreigh());
            map.put("库存", commodityManage.getInsock());
            map.put("所需兑换积分", commodityManage.getPintsRedeem());
            map.put("商品详情图", commodityManage.getDetailsMap());
            map.put("商品已售", commodityManage.getProductSold());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
